package cn.hznc.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hznc.domain.entity.UserEntity;
import cn.hznc.exception.UserException;
import cn.hznc.permission.Permission;
import cn.hznc.repository.UserRepository;
import cn.hznc.utils.JwtHelper;
import com.alibaba.excel.util.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * @Author：Administrator
 * @Date：2023/11/13 11:31
 */
@Component
public class MyInterceptor implements HandlerInterceptor{

    @Resource
    private UserRepository userRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //处理预检请求
        if(request.getRequestURI() != null){
            if("OPTIONS".equals(request.getRequestURI())){
                return false;
            }
        }
        // 从 http 请求头中取出 token
        String token = request.getHeader("Authorization");
        // 如果不是映射到方法直接通过
//        if(!(handler instanceof HandlerMethod)){
//            return true;
//        }
        //System.out.println("token = " + token);
//        String token1 = SystemInit.user.getToken();
//        if (StringUtils.isBlank(token) || !token.equals(token1) || ObjectUtil.isNull(SystemInit.user.getId())) {
//            throw new UserException("303" , "请先登录");
//        }
        if(StringUtils.isBlank(token)){
            throw new UserException("303" , "请先登录");
        }

         //获取 token中的userId,根据userId查询数据库，检查用户是否存在
        Long userId;
        try {
            userId = JwtHelper.getUserId(token);
        } catch (Exception j) {
            throw new UserException("401" , "登录信息过期,请重新登录");
        }
        if(ObjectUtil.isNull(userId)){
            return false;
        }
        int userIdInt = userId.intValue();
        UserEntity user = userRepository.selectbyUserid(userIdInt);
        if (user == null) {
            throw new UserException("303" , "请先登录");
        }

//        if (userIdInt != SystemInit.user.getId()) {
//            throw new UserException("303" , "请先登录");
//        }


        //校验许可
        if (!hasPermission(user.getId(), handler)) {
            response.getWriter().write("{\"code\":366,\"msg\":\"privilege is not enough\",\"data\":null}");
            return false;
        }
        return true;
    }

    private Boolean hasPermission(Integer userId , Object handler){
        //获取用户对应的permissionCode列表 之后获取方法注解上的permissionCode 对比
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取方法上的注解
            Permission permission = handlerMethod.getMethod().getAnnotation(Permission.class);
            if(ObjectUtil.isNull(permission)){
                return true;
            }
            String[] permissions = permission.permissions();
            List<String> permissionCodes = userRepository.selectPermissionListByUserId(userId);
            return new HashSet<>(permissionCodes).containsAll(Arrays.asList(permissions));
        }
        return true;
    }
}
